package com.tjakus.arduino.encoder;

import java.sql.Timestamp;
import java.util.Date;

import com.tjakus.arduino.hibernate.HibernateUtil;
import com.tjakus.arduino.hibernate.Sensors;
import com.tjakus.arduino.hibernate.Statistics;
import com.tjakus.arduino.logging.Logging;


public class CommandEncoder {

	/**
	 * This Method is called when a command is received and needs to be encoded
	 */

	public static void encodeCommand(String receivedCommand) {
		Logging.getLogger().info(
				"CommandEncoder - encodeCommand [ " + receivedCommand + " ]");
		String[] splitCommand = receivedCommand.split("#");
		// If received command from Arduino starts with ARD#
		if (splitCommand.length == 4 && receivedCommand.contains("ARD#")) {
			Logging.getLogger().debug(
					"CommandEncoder - encodeCommand - SensorType [ " + splitCommand[1]
							+ " ]");
			Logging.getLogger().debug(
					"CommandEncoder - encodeCommand - SensorId [ " + splitCommand[2]
							+ " ]");
			Logging.getLogger().debug(
					"CommandEncoder - encodeCommand - SensorValue [ " + splitCommand[3]
							+ " ]");
			// Create current timestamp
			Date date = new Date();
			Timestamp timestamp = new Timestamp(date.getTime());
			// Create statistic from sensor data
			Statistics statistic = new Statistics();
			statistic.setSensorId(splitCommand[2]);
			statistic.setSensorValue(splitCommand[3]);
			statistic.setTimestamp(timestamp);
			// Save statistic in database
			HibernateUtil.addStatistic(statistic);
			
			// Update current sensor values
			Sensors sensor = HibernateUtil.getSensorBySensorId(splitCommand[2]);
			if (sensor != null) {
				sensor.setValue(splitCommand[3]);
				sensor.setTimestamp(timestamp);
				HibernateUtil.updateSensor(sensor);
			}
			
		} else {
			Logging.getLogger().error(
					"CommandEncoder - encodeCommand [ Unknown data ]");
		}
	}

}
